<?php

namespace App\Http\Controllers\Common;

use App\Exports\DemoExport;
use App\Http\Controllers\Controller;
use App\Imports\DemoImport;
use App\Models\Constant\UploadConstant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Kkokk\Poster\PosterManager;
use Maatwebsite\Excel\Facades\Excel;

abstract class CommonController extends Controller {

    protected $getCol = ['*'];
    protected $instance;


    public function getQr(string $name,string $content ){
        $path = "/storage/qr/$name.png";
        if(file_exists(public_path($path))){
            return $path;
        }
        $qr = PosterManager::Poster()->Qr($content,public_path($path));
        return $path;
    }

    public function download(Request $request) {
        $module = $request->input('module','user');
        $conditions = $request->input();
        if($module=='user'){
            return Excel::download(new DemoExport($conditions),$module.'.xlsx');
        } elseif($module=='userTemplate'){
            return response()->download(public_path('UserTemplate.xlsx'));
        }
    }

    public function importFile(Request $request) {
        /* $token = $request->header('token');
         $id = checkJWT($token)['id'];
         $guardUser = GuardUser::where(compact('id'))->first();
         if(empty($guardUser)){
             return responseFail('当前用户无效！');
         }*/
        $module = $request->input('module','user');
        $file = $request->file('file');
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $path = $file->store($module,'upload');

        if($module=='user'){
            $import = new DemoImport();
        }elseif ($module=='xxx'){
            //TODO
        }else{

        }

        Excel::import($import, storage_path('app/public/upload/'.$path));
        $count = $import->count;
        $countSuccess = $import->countSuccess;
        $countFail = $import->countFail;
        $success = $import->success;
        $msg = $import->msg;
        if($success){
            return responseSuccess(compact('count','countSuccess','countFail'),0,$msg);
        }else{
            return responseFail($msg);
        }
    }

    public function upload(Request $request){
        $file = $request->file('file');
        $count = $request->input('count',0);
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $size =  $file->getSize();
        $ext = $file->getClientOriginalExtension();
        $originName = $file->getClientOriginalName();
        $module = $request->input('module','default');
        $type = $request->input('type','default');

        //检查目录
        $middlePath = "/$module/".date('Y-m-d');
        $absDir = Storage::disk('upload')->path($middlePath);
        if(!is_dir($absDir)){mkdir($absDir,0777,true);}

        //重命名
        $fileName = time().uniqid().".$ext";

        //如果是图片
        if(in_array($ext, UploadConstant::mapPic)){

            if($request->has('w')){
                $w = $request->input('w');
                $h = $request->input('h');
                if(!empty($w) && !empty($h)){
                    $this->validate($request, [
                        'file' => 'mimes:jpeg,bmp,png,gif,webp|dimensions:width='.$w.',height='.$h,
                    ],[],['w'=>'宽', 'h'=>'高',]);
                }
            }

            $imgIsCut = $request->input('imgIsCut',env('IMG_IS_CUT',false));//是否需要压缩
            $imgIsCutSize = $request->input('imgIsCutSize',env('IMG_IS_CUT_SIZE',1024*1024*1));//压缩阈值
            $imgCutRatio = $request->input('imgCutRatio',env('IMG_CUT_RATION',700));//压缩比

            //如果需要压缩
            if($imgIsCut && $size>=$imgIsCutSize){
                $fileName = time().uniqid().'.jpg';
                $rs = Image::make($file->getRealPath())->resize($imgCutRatio, $imgCutRatio, function ($constraint) {
                    $constraint->aspectRatio();
                })->save($absDir."/$fileName");
                if($rs === false){
                    return responseFail('图片压缩失败');
                }
                $filePath = "$middlePath/$fileName";
            }else{
                $filePath = $file->storeAs($middlePath,$fileName,'upload');
            }
        }
        //如果是文件
        else{
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
        }

        $filePath = Str::replace('//', '/', '/storage/upload/'.$filePath);
        $url = asset($filePath);

        if(in_array($ext, UploadConstant::mapVideo)){
            $url = asset('/common/image/cover.png');
        }

        return responseSuccess(compact('type','filePath','count','size','url','originName','ext','fileName'));
    }


    protected function handleChildren(&$records) {
        foreach ($records as $record) {
            if(count($record['children'])<=0){
                unset($record['children']);
            }else{
                $this->handleChildren($record['children']);
            }
        }
    }


    public function detail(Request $request) {
        $id = $request->input('id',0);
        $this->validate($request, ['id'=>'required|Integer']);
        $record = $this->instance->getRecordById($id);
        return responseSuccess($record->toArray());
    }

    public function change(Request $request){
        $id = $request->input('id',0);
        $info = $request->except('id');
        $this->validate($request, ['id'=>'required|Integer']);
        $updateTotal = $this->instance->changeColById($id,$info);
        return responseSuccess([],$updateTotal);
    }

    public function del(Request $request) {
        $id = $request->input('id',0);
        $this->validate($request, ['id'=>'required']);
        $this->instance->delRecordsById($id);
        return responseSuccess();
    }

}
